package com.custom.base.util

import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Rect
import android.graphics.drawable.AnimationDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Looper
import android.util.DisplayMetrics
import android.util.TypedValue
import android.view.*
import android.view.inputmethod.InputMethodManager
import android.webkit.WebView
import android.widget.*
import com.github.jdsjlzx.recyclerview.LRecyclerView
import com.custom.base.base.BaseRecyclerAdapter
import com.custom.base.manager.SDActivityManager
import com.custom.base.view.NullDataView

/**
 * 作者：
 * 时间：2017/11/27/027
 * 说明：
 */

object SDViewUtil {
    /**
     * 判断当前线程是否是UI线程.
     *
     * @return
     */
    val isUIThread: Boolean
        get() = Looper.getMainLooper() == Looper.myLooper()

    // -------------------------layoutParams
    // LinearLayout
    val layoutParamsLinearLayoutWW: LinearLayout.LayoutParams
        get() = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )

    val layoutParamsLinearLayoutMM: LinearLayout.LayoutParams
        get() = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT
        )

    val layoutParamsLinearLayoutMW: LinearLayout.LayoutParams
        get() = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )

    val layoutParamsLinearLayoutWM: LinearLayout.LayoutParams
        get() = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.MATCH_PARENT
        )

    // RelativeLayout
    val layoutParamsRelativeLayoutWW: RelativeLayout.LayoutParams
        get() = RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT
        )

    val layoutParamsRelativeLayoutMM: RelativeLayout.LayoutParams
        get() = RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT
        )

    val layoutParamsRelativeLayoutMW: RelativeLayout.LayoutParams
        get() = RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT
        )

    val layoutParamsRelativeLayoutWM: RelativeLayout.LayoutParams
        get() = RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.MATCH_PARENT
        )

    // FrameLayout
    val layoutParamsFrameLayoutWW: FrameLayout.LayoutParams
        get() = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT
        )

    val layoutParamsFrameLayoutMM: FrameLayout.LayoutParams
        get() = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT,
            FrameLayout.LayoutParams.MATCH_PARENT
        )

    val layoutParamsFrameLayoutMW: FrameLayout.LayoutParams
        get() = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT,
            FrameLayout.LayoutParams.WRAP_CONTENT
        )

    val layoutParamsFrameLayoutWM: FrameLayout.LayoutParams
        get() = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.MATCH_PARENT
        )

    // ViewGroup
    val layoutParamsViewGroupWW: ViewGroup.LayoutParams
        get() = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )

    val layoutParamsViewGroupMM: ViewGroup.LayoutParams
        get() = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )

    val layoutParamsViewGroupMW: ViewGroup.LayoutParams
        get() = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )

    val layoutParamsViewGroupWM: ViewGroup.LayoutParams
        get() = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )

    // ------------------------layoutInflater
    val layoutInflater: LayoutInflater
        get() = LayoutInflater.from(SDActivityManager.instance.lastActivity?.application)

    val displayMetrics: DisplayMetrics
        get() = SDActivityManager.instance.lastActivity?.application?.resources!!.displayMetrics

    fun inflate(resource: Int, root: ViewGroup?): View {
        return layoutInflater.inflate(resource, root)
    }

    fun inflate(resource: Int, root: ViewGroup?, attachToRoot: Boolean): View {
        return layoutInflater.inflate(resource, root, attachToRoot)
    }
    /**
     * 获取屏幕宽度
     *
     * @return
     */
    val screenWidth: Int
        get() {
            val metrics = displayMetrics
            return metrics.widthPixels
        }

    /**
     * 获取屏幕高度
     *
     * @return
     */
    val screenHeight: Int
        get() {
            val metrics = displayMetrics
            return metrics.heightPixels
        }

    /**
     * 获取密度
     *
     * @return
     */
    val density: Float
        get() = SDActivityManager.instance.lastActivity?.application?.resources!!.displayMetrics.density

    val scaledDensity: Float
        get() = SDActivityManager.instance.lastActivity?.application?.resources!!.displayMetrics.scaledDensity

    /**
     * 获取状态栏高度
     *
     * @return
     */
    val statusBarHeight: Int
        get() {
            var result = 0
            val resourceId =
                SDActivityManager.instance.lastActivity?.application?.resources?.getIdentifier("status_bar_height", "dimen", "android")
            if (resourceId != null) {
                if (resourceId > 0) {
                    result = SDActivityManager.instance.lastActivity?.application?.resources!!.getDimensionPixelSize(
                        resourceId
                    )
                }
            }
            return result
        }

    /**
     * 获取资源id
     *
     * @param context
     * @param id
     * @return
     */
    fun getRId( id: Int): View {
        return getRId(SDActivityManager.instance.lastActivity!!,id)
    }
    fun getRId(context: Context, id: Int): View {
        return LayoutInflater.from(context).inflate(id, null)
    }

    /**
     * 隐藏输入法
     */
    @JvmOverloads
    fun hideInputMethod(
        view: View,
        context: Context = SDActivityManager.instance.lastActivity?.application!!
    ) {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (imm.isActive) {
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }

    /**
     * 显示输入法
     *
     * @param context
     * @param view
     * @param delay
     */
    @JvmOverloads
    fun showInputMethod(
        view: View,
        context: Context = SDActivityManager.instance.lastActivity?.application!!,
        delay: Long = 0
    ) {
        var delay = delay
        if (delay < 0) {
            delay = 0
        }

        SDHandlerUtil.runOnUiThreadDelayed(Runnable {
            view.isFocusable = true
            view.isFocusableInTouchMode = true
            view.requestFocus()
            val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(view, InputMethodManager.SHOW_FORCED)
        }, delay)
    }

    /**
     * 重置listView高度，解决和scrollview嵌套问题
     *
     * @param listView
     */
    fun resetListViewHeightBasedOnChildren(listView: ListView) {
        val totalHeight = getListViewTotalHeight(listView)
        if (totalHeight > 0) {
            val params = listView.layoutParams
            params.height = totalHeight
            params.height += 5
            listView.layoutParams = params
        }
    }

    /**
     * 设置背景图片drawable
     *
     * @param view
     * @param drawable
     */
    fun setBackgroundDrawable(view: View, drawable: Drawable) {
        val paddingTop = view.paddingTop
        val paddingBottom = view.paddingBottom
        val paddingLeft = view.paddingLeft
        val paddingRight = view.paddingRight
        view.setBackgroundDrawable(drawable)
        view.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom)
    }

    /**
     * 设置背景图片resource
     *
     * @param view
     * @param resId
     */
    fun setBackgroundResource(view: View, resId: Int) {
        val paddingTop = view.paddingTop
        val paddingBottom = view.paddingBottom
        val paddingLeft = view.paddingLeft
        val paddingRight = view.paddingRight
        view.setBackgroundResource(resId)
        view.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom)
    }

    /**
     * 设置scrollView的Y
     *
     * @param sv
     * @param y
     * @param delay
     */
    @SuppressLint("NewApi")
    fun scrollToViewY(sv: ScrollView?, y: Int, delay: Int) {
        if (sv != null && delay >= 0) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                SDHandlerUtil.runOnUiThreadDelayed(Runnable {
                    sv.scrollTo(
                        0,
                        y
                    )
                }, delay.toLong())
            }
        }
    }

    /**
     * 屏幕宽度的百分比
     *
     * @param percent 0-1
     * @return
     */
    fun getScreenWidthPercent(percent: Float): Int {
        return (screenWidth.toFloat() * percent).toInt()
    }

    /**
     * 屏幕高度的百分比
     *
     * @param percent 0-1
     * @return
     */
    fun getScreenHeightPercent(percent: Float): Int {
        return (screenHeight.toFloat() * percent).toInt()
    }

    /**
     * sp转px
     *
     * @param sp
     * @return
     */
    fun sp2px(sp: Float): Float {
        val fontScale = displayMetrics.scaledDensity
        return (sp * fontScale + 0.5f)
    }

    /**
     * dp转px
     *
     * @param dp
     * @return
     */
    fun dp2px(dp: Float): Float {
        val scale = displayMetrics.density
        return (dp * scale + 0.5f)
    }
    /**
     * dp转px
     *
     * @param dp
     * @return
     */
    fun dp2pxInt(dp: Int): Int {
        val scale = displayMetrics.density
        return ((dp * scale + 0.5f).toInt())
    }

    /**
     * px转dp
     *
     * @param px
     * @return
     */
    fun px2dp(px: Float): Int {
        val scale = displayMetrics.density
        return (px / scale + 0.5f).toInt()
    }

    /**
     * px转sp
     *
     * @param px
     * @return
     */
    fun px2sp(px: Float): Int {
        val scale = displayMetrics.density
        return (px / scale + 0.5f).toInt()
    }

    /**
     * 获取标高
     *
     * @param originalWidth
     * @param originalHeight
     * @param scaleWidth
     * @return
     */
    fun getScaleHeight(originalWidth: Int, originalHeight: Int, scaleWidth: Int): Int {
        var result = 0
        if (originalWidth != 0) {
            result = originalHeight * scaleWidth / originalWidth
        }
        return result
    }

    /**
     * 获取标宽
     *
     * @param originalWidth
     * @param originalHeight
     * @param scaleHeight
     * @return
     */
    fun getScaleWidth(originalWidth: Int, originalHeight: Int, scaleHeight: Int): Int {
        var result = 0
        if (originalHeight != 0) {
            result = originalWidth * scaleHeight / originalHeight
        }
        return result
    }

    /**
     * 获取listView的总高度
     *
     * @param listView
     * @return
     */
    fun getListViewTotalHeight(listView: ListView): Int {
        val listAdapter = listView.adapter ?: return 0
        return getListViewHeightRange(
            listView,
            0,
            listAdapter.count - 1
        )
    }

    /**
     * 获取listview的范围高度
     *
     * @param listView
     * @param start
     * @param end
     * @return
     */
    fun getListViewHeightRange(listView: ListView, start: Int, end: Int): Int {
        val listAdapter = listView.adapter ?: return 0
        var totalHeight = 0
        if (start in 0..end && end < listAdapter.count) {
            for (i in start..end) {
                val listItem = listAdapter.getView(i, null, listView)
                if (listItem != null) {
                    listItem.measure(0, 0)
                    val height = listItem.measuredHeight
                    val dividerHeight = listView.dividerHeight * (listAdapter.count - 1)
                    totalHeight += height + dividerHeight
                }
            }
        }
        return totalHeight
    }

    /**
     * 测量角度
     *
     * @param v
     */
    fun measureView(v: View) {
        val w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        val h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        v.measure(w, h)
    }

    /**
     * 获取控件的高度
     *
     * @param view
     * @return
     */
    fun getViewHeight(view: View): Int {
        var height = 0
        height = view.height
        if (height <= 0) {
            measureView(view)
            height = view.measuredHeight
        }
        return height
    }

    /**
     * 获取控件包含控件内的高度
     *
     * @param view
     * @return
     */
    fun getViewHeightAll(view: View): Int {
        var height = getViewHeight(view)
        val params = getViewMarginLayoutParams(view)
        if (params != null) {
            height += params.topMargin + params.bottomMargin
        }
        return height
    }

    /**
     * 获取控件的宽度
     *
     * @param view
     * @return
     */
    fun getViewWidth(view: View): Int {
        var width = 0
        width = view.width
        if (width <= 0) {
            measureView(view)
            width = view.measuredWidth
        }
        return width
    }

    /**
     * 获取控件包含控件内的宽度
     *
     * @param view
     * @return
     */
    fun getViewWidthAll(view: View): Int {
        var width = getViewWidth(view)
        val params = getViewMarginLayoutParams(view)
        if (params != null) {
            width += params.leftMargin + params.rightMargin
        }
        return width
    }

    /**
     * 如果数组没有内容就隐藏view
     */
    fun toggleEmptyMsgByList(list: List<Any>?, emptyView: View?) {
        if (emptyView != null) {
            if (list != null && list.isNotEmpty()) {
                hide(emptyView)
            } else {
                show(emptyView)
            }
        }
    }
    /**
     * 如果数组没有内容就显示view
     */
    fun toggleViewByList(list: List<Any>?, view: View?) {
        if (view != null) {
            if (list != null && list.isNotEmpty()) {
                show(view)
            } else {
                hide(view)
            }
        }
    }

    /**
     * 更新adapter数据
     */
    fun <T> updateAdapterByList(
        listOriginalData: MutableList<T>?,
        listNewData: List<T>?,
        mAdapter: BaseRecyclerAdapter<T>? = null,
        isLoadMore: Boolean = false,//是否添加到末尾
        listView: LRecyclerView? = null,
        nullData:NullDataView? = null
    ) {
        listOriginalData?.apply {
            if(listNewData!=null&& listNewData.isNotEmpty()){// 有新数据
                if (!isLoadMore) {
                    listOriginalData.clear()
                }
                listOriginalData.addAll(listNewData)
                nullData?.visibility = View.GONE
            }else{
                if (!isLoadMore) {
                    listOriginalData.clear()
                    nullData?.visibility = View.VISIBLE
                }
                //如果没有更多数据（也就是全部加载完成），加上如下代码：
                listView?.setNoMore(true)
            }
            mAdapter?.apply {
                notifyDataSetChanged()
            }
        }
    }
    /**
     * 更新adapter数据
     */
    fun <T> updateAdapterByArrayList(
        listOriginalData: MutableList<T>?,
        listNewData: ArrayList<T>?,
        mAdapter: BaseRecyclerAdapter<T>? = null,
        isLoadMore: Boolean = false,//是否添加到末尾
        listView: LRecyclerView? = null,
        nullData:NullDataView? = null
    ) {
        listOriginalData?.apply {
            if(listNewData!=null&& listNewData.isNotEmpty()){// 有新数据
                if (!isLoadMore) {
                    listOriginalData.clear()
                }
                listOriginalData.addAll(listNewData)
                nullData?.visibility = View.GONE
            }else{
                if (!isLoadMore) {
                    listOriginalData.clear()
                    nullData?.visibility = View.VISIBLE
                }
                //如果没有更多数据（也就是全部加载完成），加上如下代码：
                listView?.setNoMore(true)
            }
            mAdapter?.apply {
                notifyDataSetChanged()
            }
        }
    }

    /**
     * 控件内添加title
     */
    fun wrapperTitle(contentLayoutId: Int, titleLayoutId: Int): View {
        val inflater = LayoutInflater.from(SDActivityManager.instance.lastActivity?.application)
        val contentView = inflater.inflate(contentLayoutId, null)
        val titleView = inflater.inflate(titleLayoutId, null)
        return wrapperTitle(contentView, titleView)
    }
    /**
     * 控件内添加title
     */
    fun wrapperTitle(contentView: View, titleView: View): View {
        val linAll = LinearLayout(SDActivityManager.instance.lastActivity?.application)
        linAll.orientation = LinearLayout.VERTICAL
        val paramsTitle = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        val paramsContent = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT
        )
        linAll.addView(titleView, paramsTitle)
        linAll.addView(contentView, paramsContent)
        return linAll
    }
    /**
     * 控件内添加title
     */
    fun wrapperTitle(contentView: View, titleLayoutId: Int): View {
        val inflater = LayoutInflater.from(SDActivityManager.instance.lastActivity?.application)
        val titleView = inflater.inflate(titleLayoutId, null)
        return wrapperTitle(contentView, titleView)
    }

    /**
     * 设置控件高度
     * @param view
     * @param height
     * @return
     */
    fun setViewHeight(view: View, height: Int): Boolean {
        val params = view.layoutParams
        if (params != null) {
            if (params.height != height) {
                params.height = height
                view.layoutParams = params
            }
            return true
        }
        return false
    }

    /**
     * 设置控件宽度
     * @param view
     * @param width
     * @return
     */
    fun setViewWidth(view: View, width: Int): Boolean {
        val params = view.layoutParams
        if (params != null) {
            if (params.width != width) {
                params.width = width
                view.layoutParams = params
            }
            return true
        }
        return false
    }

    /**
     * 重置控件的高度
     * @param view
     */
    fun resetViewHeight(view: View) {
        setViewHeight(
            view,
            getViewHeight(view)
        )
    }

    /**
     * 重置控件的宽度
     * @param view
     */
    fun resetViewWidth(view: View) {
        setViewWidth(
            view,
            getViewWidth(view)
        )
    }

    /**
     * 影藏控件
     * @param view
     */
    fun hide(view: View?) {
        if (view != null && view.visibility != View.GONE) {
            view.visibility = View.GONE
        }
    }

    /**
     * 影藏控件占着位置
     * @param view
     */
    fun invisible(view: View?) {
        if (view != null && view.visibility != View.INVISIBLE) {
            view.visibility = View.INVISIBLE
        }
    }

    /**
     * 显示控件
     * @param view
     */
    fun show(view: View?) {
        if (view != null && view.visibility != View.VISIBLE) {
            view.visibility = View.VISIBLE
        }
    }

    /**
     * 切换控件的影藏状态
     * @param view
     * @return
     */
    fun toggleGone(view: View?): Boolean {
        var result = false
        if (view != null) {
            val visibility = view.visibility
            if (visibility == View.VISIBLE) {
                view.visibility = View.GONE
                result = false
            } else if (visibility == View.GONE) {
                view.visibility = View.VISIBLE
                result = true
            }
        }
        return result
    }

    /**
     * 切换控件的影藏状态Invisible
     * @param view
     * @return
     */
    fun toggleInvisible(view: View?): Boolean {
        var result = false
        if (view != null) {
            val visibility = view.visibility
            if (visibility == View.VISIBLE) {
                view.visibility = View.INVISIBLE
                result = false
            } else if (visibility == View.INVISIBLE) {
                view.visibility = View.VISIBLE
                result = true
            }
        }
        return result
    }

    /**
     * 获取在其窗口中计算该视图的坐标
     * @param view
     * @return
     */
    fun getLocationInWindow(view: View?): IntArray? {
        var location: IntArray? = null
        if (view != null) {
            location = IntArray(2)
            view.getLocationInWindow(location)
        }
        return location
    }

    /**
     * 获取在屏幕上计算该视图的坐标
     * @param view
     * @return
     */
    fun getLocationOnScreen(view: View?): IntArray? {
        var location: IntArray? = null
        if (view != null) {
            location = IntArray(2)
            view.getLocationOnScreen(location)
        }
        return location
    }

    /**
     * 获取去掉状态栏后计算该视图的坐标
     * @param view
     * @return
     */
    fun getLocationOnScreenWithoutStatusBar(view: View): IntArray? {
        val location = getLocationOnScreen(view)
        if (location != null) {
            val statusBarHeight = statusBarHeight
            location[1] -= statusBarHeight
        }
        return location
    }

    /**
     * 动态设置字体SP格式的大小
     * @param view
     * @param sizeSp 字体大小
     */
    fun setTextSizeSp(view: TextView, sizeSp: Float) {
        view.setTextSize(TypedValue.COMPLEX_UNIT_SP, sizeSp)
    }


    /**
     * 设置webView缩放控制可见性
     * @param webView
     * @param visibility
     */
    fun setWebviewZoomControlVisibility(webView: View, visibility: Int) {
        try {
            val field = WebView::class.java.getDeclaredField("mZoomButtonsController")
            field.isAccessible = true
            val mZoomButtonsController = ZoomButtonsController(webView)
            mZoomButtonsController.zoomControls.visibility = visibility
            field.set(webView, mZoomButtonsController)
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    /**
     * 是完全可见的第一个Item
     * @param absListView
     * @return
     */
    fun isFirstItemTotallyVisible(absListView: AbsListView): Boolean {
        val adapter = absListView.adapter
        if (null == adapter || adapter.isEmpty) {
            return true
        } else {
            if (absListView.firstVisiblePosition <= 1) {
                val firstVisibleChild = absListView.getChildAt(0)
                if (firstVisibleChild != null) {
                    return firstVisibleChild.top >= 0
                }
            }
        }
        return false
    }

    /**
     * 是完全可见的最后一个Item
     * @param absListView
     * @return
     */
    fun isLastItemTotallyVisible(absListView: AbsListView): Boolean {
        val adapter = absListView.adapter
        if (null == adapter || adapter.isEmpty) {
            return true
        } else {
            val lastItemPosition = absListView.count - 1
            val lastVisiblePosition = absListView.lastVisiblePosition
            if (lastVisiblePosition >= lastItemPosition - 1) {
                val childIndex = lastVisiblePosition - absListView.firstVisiblePosition
                val lastVisibleChild = absListView.getChildAt(childIndex)
                if (lastVisibleChild != null) {
                    return lastVisibleChild.bottom <= absListView.bottom
                }
            }
        }
        return false
    }

    /**
     * 从父视图中删除视图
     * @param child
     */
    fun removeViewFromParent(child: View?) {
        if (child != null) {
            val parent = child.parent
            if (parent is ViewGroup) {
                parent.removeView(child)
            }
        }
    }

    /**
     * 创建视图的位图
     * @param view
     * @return
     */
    fun createViewBitmap(view: View?): Bitmap? {
        val bmp: Bitmap? = null
        if (view != null) {
            view.isDrawingCacheEnabled = true
            Bitmap.createBitmap(view.drawingCache)
            view.destroyDrawingCache()
        }
        return bmp
    }

    /**
     * 获取控件在窗口可见区域
     * @param view
     * @return
     */
    fun getWindowVisibleDisplayFrame(view: View?): Rect {
        val rect = Rect()
        view?.getWindowVisibleDisplayFrame(rect)
        return rect
    }

    /**
     * 获取控件在在屏幕上的X
     * @param view
     * @return
     */
    fun getViewXOnScreen(view: View?): Int {
        val location = IntArray(2)
        view?.getLocationOnScreen(location)
        return location[0]
    }

    /**
     * 获取控件在在屏幕上的Y
     * @param view
     * @return
     */
    fun getViewYOnScreen(view: View?): Int {
        val location = IntArray(2)
        view?.getLocationOnScreen(location)
        return location[1]
    }

    /**
     * 获取屏幕上的控件位置
     * @param view
     * @return
     */
    fun getViewLocationOnScreen(view: View?): IntArray {
        val location = IntArray(2)
        view?.getLocationOnScreen(location)
        return location
    }

    /**
     * 获取视图中心在屏幕上的X位置
     * @param view
     * @return
     */
    fun getViewCenterXOnScreen(view: View?): Int {
        var x = 0
        if (view != null) {
            x = getViewXOnScreen(view)
            val width = getViewWidth(view)
            x = x + width / 2
        }
        return x
    }

    /**
     * 获取视图中心在屏幕上的Y位置
     * @param view
     * @return
     */
    fun getViewCenterYOnScreen(view: View?): Int {
        var y = 0
        if (view != null) {
            y = getViewYOnScreen(view)
            val height = getViewHeight(view)
            y = y + height / 2
        }
        return y
    }

    /**
     * 获取控件在屏幕上的区域
     * @param view
     * @return
     */
    fun getViewRect(view: View?): Rect {
        val r = Rect()
        if (view != null && view.visibility == View.VISIBLE) {
            val location = getViewLocationOnScreen(view)
            r.left = location[0]
            r.right = r.left + getViewWidth(view)
            r.top = location[1]
            r.bottom = r.top + getViewHeight(view)
        }
        return r
    }

    /**
     * 判断点击的点是否在控件的区域内
     * @param view
     * @param x
     * @param y
     * @return
     */
    fun isTouchView(view: View, x: Int, y: Int): Boolean {
        var result = false
        val r = getViewRect(view)
        result = r.contains(x, y)
        return result
    }

    /**
     * 判断点击的点的Y轴是否在控件的区域内
     * @param view
     * @param x
     * @param y
     * @return
     */
    fun isTouchViewY(view: View, y: Int): Boolean {
        var result = false
        val r = getViewRect(view)
        result = r.left < r.right && r.top < r.bottom && y >= r.top && y < r.bottom
        return result
    }

    /**
     * 判断点击的点的X轴是否在控件的区域内
     * @param view
     * @param x
     * @param y
     * @return
     */
    fun isTouchViewX(view: View, x: Int): Boolean {
        var result = false
        val r = getViewRect(view)
        result = r.left < r.right && r.top < r.bottom && x >= r.left && x < r.right
        return result
    }

    /**
     * 判断点击时间的点是否在控件的区域内
     * @param view
     * @param e
     * @return
     */
    fun isTouchView(view: View, e: MotionEvent?): Boolean {
        var result = false
        if (e != null) {
            result = isTouchView(view, e.rawX.toInt(), e.rawY.toInt())
        }
        return result
    }

    /**
     * 设置控件的MarginTop
     * @param view
     * @param top
     */
    fun setViewMarginTop(view: View, top: Int) {
        val p = getViewMarginLayoutParams(view)
        if (p != null) {
            p.topMargin = top
            view.layoutParams = p
        }
    }

    /**
     * 设置控件的MarginLeft
     * @param view
     * @param left
     */
    fun setViewMarginLeft(view: View, left: Int) {
        val p = getViewMarginLayoutParams(view)
        if (p != null) {
            p.leftMargin = left
            view.layoutParams = p
        }
    }

    /**
     * 设置控件的MarginBottom
     * @param view
     * @param bottom
     */
    fun setViewMarginBottom(view: View, bottom: Int) {
        val p = getViewMarginLayoutParams(view)
        if (p != null) {
            p.bottomMargin = bottom
            view.layoutParams = p
        }
    }

    /**
     * 设置控件的MarginRight
     * @param view
     * @param right
     */
    fun setViewMarginRight(view: View, right: Int) {
        val p = getViewMarginLayoutParams(view)
        if (p != null) {
            p.rightMargin = right
            view.layoutParams = p
        }
    }

    /**
     * 设置控件的Margin
     * @param view
     * @param left
     * @param top
     * @param right
     * @param bottom
     */
    fun setViewMargin(view: View, left: Int, top: Int, right: Int, bottom: Int) {
        val p = getViewMarginLayoutParams(view)
        if (p != null) {
            p.topMargin = top
            p.leftMargin = left
            p.bottomMargin = bottom
            p.rightMargin = right
            view.layoutParams = p
        }
    }

    /**
     * 设置控件的Margins
     * @param view
     * @param margins
     */
    fun setViewMargins(view: View, margins: Int) {
        setViewMargin(view, margins, margins, margins, margins)
    }

    /**
     * 获取控件的MarginLayoutParams
     * @param view
     * @return
     */
    fun getViewMarginLayoutParams(view: View?): ViewGroup.MarginLayoutParams? {
        var result: ViewGroup.MarginLayoutParams? = null
        if (view != null) {
            val params = view.layoutParams
            if (params != null && params is ViewGroup.MarginLayoutParams) {
                result = params
            }
        }
        return result
    }

    /**
     * 设置控件的PaddingLeft
     * @param view
     * @param left
     */
    fun setViewPaddingLeft(view: View, left: Int) {
        setViewPadding(
            view,
            left,
            view.paddingTop,
            view.paddingRight,
            view.paddingBottom
        )
    }

    /**
     * 设置控件的PaddingTop
     * @param view
     * @param top
     */
    fun setViewPaddingTop(view: View, top: Int) {
        setViewPadding(
            view,
            view.paddingLeft,
            top,
            view.paddingRight,
            view.paddingBottom
        )
    }

    /**
     * 设置控件的PaddingRight
     * @param view
     * @param right
     */
    fun setViewPaddingRight(view: View, right: Int) {
        setViewPadding(
            view,
            view.paddingLeft,
            view.paddingTop,
            right,
            view.paddingBottom
        )
    }

    /**
     * 设置控件的PaddingBottom
     * @param view
     * @param bottom
     */
    fun setViewPaddingBottom(view: View, bottom: Int) {
        setViewPadding(
            view,
            view.paddingLeft,
            view.paddingTop,
            view.paddingRight,
            bottom
        )
    }

    /**
     * 设置控件的Padding
     * @param view
     * @param left
     * @param top
     * @param right
     * @param bottom
     */
    fun setViewPadding(view: View, left: Int, top: Int, right: Int, bottom: Int) {
        view.setPadding(left, top, right, bottom)
    }

    /**
     * 设置控件的Paddings
     * @param view
     * @param paddings
     */
    fun setViewPaddings(view: View, paddings: Int) {
        setViewPadding(view, paddings, paddings, paddings, paddings)
    }

    /**
     * 显示PopupWindow并且设置marginBottom
     * @param pop
     * @param view
     * @param marginBottom
     */
    fun showPopTop(pop: PopupWindow, view: View, marginBottom: Int) {
        val location = getLocationOnScreen(view)
        val x = location!![0] - screenWidth / 2 + view.width / 2
        val y = view.height + marginBottom
        pop.showAtLocation(view, Gravity.BOTTOM, x, y)
    }

    /**
     * 显示PopupWindow并且设置marginRight
     * @param pop
     * @param view
     * @param marginRight
     */
    fun showPopLeft(pop: PopupWindow, view: View, marginRight: Int) {
        val location = getLocationOnScreen(view)
        pop.showAtLocation(
            view,
            Gravity.NO_GRAVITY,
            location!![0] - pop.width - marginRight,
            location[1]
        )
    }

    /**
     * 显示PopupWindow并且设置marginLeft
     * @param pop
     * @param view
     * @param marginLeft
     */
    fun showPopRight(pop: PopupWindow, view: View, marginLeft: Int) {
        val location = getLocationOnScreen(view)
        pop.showAtLocation(
            view,
            Gravity.NO_GRAVITY,
            location!![0] + view.width + marginLeft,
            location[1]
        )
    }

    /**
     * 更新图片控件的大小
     * @param imageView
     * @param drawable
     */
    fun updateImageViewSize(imageView: ImageView?, drawable: Drawable?) {
        if (drawable != null && imageView != null) {
            val width = getViewWidth(imageView)
            if (width > 0) {
                val newHeight = getScaleHeight(
                    drawable.intrinsicWidth,
                    drawable.intrinsicHeight,
                    width
                )
                setViewHeight(imageView, newHeight)
            }
        }
    }

    /**
     * 设置控件的宽度WRAP_CONTENT
     * @param view
     */
    fun setViewWidthWrapContent(view: View) {
        setViewWidth(view, ViewGroup.LayoutParams.WRAP_CONTENT)
    }

    /**
     * 设置控件的宽度MATCH_PARENT
     * @param view
     */
    fun setViewWidthMatchParent(view: View) {
        setViewWidth(view, ViewGroup.LayoutParams.MATCH_PARENT)
    }

    /**
     * 设置控件的高度WRAP_CONTENT
     * @param view
     */
    fun setViewHeightWrapContent(view: View) {
        setViewHeight(view, ViewGroup.LayoutParams.WRAP_CONTENT)
    }

    /**
     * 设置控件的高度MATCH_PARENT
     * @param view
     */
    fun setViewHeightMatchParent(view: View) {
        setViewHeight(view, ViewGroup.LayoutParams.MATCH_PARENT)
    }

    /**
     * 设置控件宽的权重weight
     * @param view
     * @param weight
     */
    fun setViewWidthWeightContent(view: View?, weight: Float) {
        if (view != null) {
            val vgParams = view.layoutParams
            if (vgParams is LinearLayout.LayoutParams) {
                if (vgParams != null) {
                    vgParams.width = 0
                    vgParams.weight = weight
                    view.layoutParams = vgParams
                }
            }
        }
    }

    /**
     * 设置控件高的权重weight
     * @param view
     * @param weight
     */
    fun setViewHeightWeightContent(view: View?, weight: Float) {
        if (view != null) {
            val vgParams = view.layoutParams
            if (vgParams is LinearLayout.LayoutParams) {
                vgParams.height = 0
                vgParams.weight = weight
                view.layoutParams = vgParams
            }
        }
    }

    /**
     * 开始动画绘制
     * @param drawable
     */
    fun startAnimationDrawable(drawable: Drawable) {
        if (drawable is AnimationDrawable) {
            if (!drawable.isRunning) {
                drawable.start()
            }
        }
    }

    /**
     * 停止动画在index的地方的绘制
     * @param drawable
     */
    @JvmOverloads
    fun stopAnimationDrawable(drawable: Drawable, stopIndex: Int = 0) {
        if (drawable is AnimationDrawable) {
            if (drawable.isRunning) {
                drawable.stop()
                drawable.selectDrawable(stopIndex)
            }
        }
    }

    /**
     * 滚动listview，当deltaY大于listview的高度的时候则该次调用只能滚动listview的高度
     * @param deltaY   滚动的距离。正值：item向下移动，负值：item向上移动
     * @param listView
     */
    @TargetApi(19)
    fun scrollListBy(deltaY: Int, listView: AbsListView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            listView.scrollListBy(-deltaY)
        } else {
            try {
                val method = AbsListView::class.java.getDeclaredMethod(
                    "trackMotionScroll",
                    Int::class.javaPrimitiveType,
                    Int::class.javaPrimitiveType
                )
                method.isAccessible = true
                method.invoke(listView, deltaY, deltaY)
            } catch (e: Exception) {
                e.printStackTrace()
            }

        }
    }

    /**
     * 获取listView下面的间距
     * @param listView
     * @return
     */
    fun getListViewBelowSpacing(listView: ListView): Int {
        var belowSpacing = 0
        val adapter = listView.adapter
        if (adapter != null) {
            val totalCount = adapter.count
            if (totalCount > 0) {
                val lastVisiblePosition = listView.lastVisiblePosition
                val lastItemBottom = listView.getChildAt(listView.childCount - 1).bottom
                val spaceBelowLastItem = lastItemBottom - listView.height
                val spaceBelowLeft =
                    getListViewHeightRange(
                        listView,
                        lastVisiblePosition + 1,
                        totalCount - 1
                    )
                belowSpacing = spaceBelowLastItem + spaceBelowLeft
            }
        }
        return belowSpacing
    }

    /**
     * 设置Activity半透明的状态
     * @param activity
     * @param on
     */
    @TargetApi(19)
    fun setTranslucentStatus(activity: Activity?, on: Boolean) {
        if (activity != null) {
            val win = activity.window
            val winParams = win.attributes
            val bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
            if (on) {
                winParams.flags = winParams.flags or bits
            } else {
                winParams.flags = winParams.flags and bits.inv()
            }
            win.attributes = winParams
        }
    }

    /**
     * 重置视图
     * @param view
     */
    fun resetView(view: View?) {
        if (view != null) {
            view.alpha = 1.0f
            view.rotation = 0.0f
            view.rotationX = 0.0f
            view.rotationY = 0.0f
            view.translationX = 0.0f
            view.translationY = 0.0f
        }
    }

    /**
     * 测量文本
     * @param textView
     * @param content
     * @return
     */
    fun measureText(textView: TextView?, content: String): Float {
        var width = 0f
        if (textView != null) {
            val textPaint = textView.paint
            width = textPaint.measureText(content)
        }
        return width
    }

    /**
     * 更换视图
     * @param viewGroup
     * @param child
     * @return
     */
    @JvmOverloads
    fun replaceView(viewGroup: View, child: View, params: ViewGroup.LayoutParams? = null): Boolean {
        return addView(viewGroup, child, params, true)
    }

    /**
     * 添加视图
     * @param viewGroup
     * @param child
     * @param params
     * @param removeAllViews
     * @return
     */
    private fun addView(
        viewGroup: View,
        child: View,
        params: ViewGroup.LayoutParams? = null,
        removeAllViews: Boolean = false
    ): Boolean {
        if (viewGroup is ViewGroup) {
            val vg = viewGroup as ViewGroup?
            vg?.apply {
                if (removeAllViews) {
                    vg.removeAllViews()
                }
            }
            removeViewFromParent(child)
            vg?.apply {
                if (params != null) {
                    vg.addView(child, params)
                } else {
                    vg.addView(child)
                }
            }
            return true
        }
        return false
    }

    /**
     * 延迟获得view的大小
     * @param view      目标view
     * @param invisible true:需要先隐藏后显示
     * @param delay     延迟多少毫秒触发
     * @param listener  回调监听
     */
    fun getViewSize(view: View?, invisible: Boolean, delay: Long, listener: SDViewSizeListener?) {
        var delay = delay
        if (view != null) {
            val width = getViewWidth(view)
            val height = getViewHeight(view)
            if (width <= 0 && height <= 0) {
                // true:需要先隐藏后显示
                if (invisible) {
                    invisible(view)
                }
                // 需要延迟
                if (delay < 0) {
                    delay = 100
                }
                SDHandlerUtil.runOnUiThreadDelayed(Runnable {
                    if (invisible) {
                        show(view)
                    }
                    listener?.onResult(view)
                }, delay)
            } else {
                listener?.onResult(view)
            }
        }
    }
    var lastClick = 0L
    /**
     * 防止快速点击
     *
     * @return
     */
    fun fastClick(): Boolean {
        if (System.currentTimeMillis() - lastClick <= 500) {
            return false
        }
        lastClick = System.currentTimeMillis()
        return true
    }

    interface SDViewSizeListener {
        fun onResult(view: View)
    }
}